import { provide, inject, reactive } from 'vue';

// 创建一个新的 Symbol 作为 provide 和 inject 的键值
const eventBusSymbol = Symbol();

// 创建一个事件总线对象
const eventBus = reactive({
  events: {},
  emit(event, ...args) {
    (this.events[event] || []).forEach(callback => callback(...args));
  },
  on(event, callback) {
    if (!this.events[event]) {
      this.events[event] = [];
    }
    this.events[event].push(callback);
  }
});

// 在应用程序的顶层组件中 provide 事件总线对象
export function provideEventBus() {
  provide(eventBusSymbol, eventBus);
}

// 在组件中使用 inject 获取事件总线对象
export function useEventBus() {
  const eventBus = inject(eventBusSymbol);
  if (!eventBus) {
    throw new Error('useEventBus must be used within a component that has been provided with the event bus.');
  }
  return eventBus;
}
